<template>

  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
    <a-layout>
      <a-layout-content  style="background: #fff;
      height: 600px;

 ">

          <a-row>
            <a-col :span="12" >
              <a-form-item label="学员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-search-select-tag v-decorator="['trainee',{ rules: [{ required: true, message: '请选择一个学员！' }]}]" dict="trainee t join sys_user s on t.user_id = s.id , realname,s.id" />
              </a-form-item>
            </a-col>
            <a-col :span="12" >
              <a-form-item label="差点" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['chadian']" placeholder="请输入差点"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row >
            <a-col :span="24" >
              <a-form-item  label="问题标题" :labelCol="demoLabelCol" :wrapperCol="wideWrapperCol" >
                <a-input v-decorator="['title',{ rules: [{ required: true, message: '请填写问题标题！' }]}]" placeholder="请输入问题标题"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row type="flex">
            <a-col :flex="12" >
              <a-form-item label="问题分类" :labelCol="demoLabelCol" :wrapperCol="wideWrapperCol">
                <j-tree-select
                  v-decorator="['questionTypeId',{ rules: [{ required: true, message: '请选择问题分类！' }]}]"
                  placeholder="请选择问题分类"
                  multiple="true"
                  :trigger-change="true"
                  dict="question_type,name,id"
                  pidField="parent_id">
                </j-tree-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :span="24">
            <a-form-item label="描述"  :labelCol="demoLabelCol" :wrapperCol="wideWrapperCol">
              <a-input v-decorator="['description']" placeholder="请输入描述"></a-input>
            </a-form-item>
          </a-row>
          <a-row :span="24">
            <a-col  >
              <a-form-item label="标签" :labelCol="demoLabelCol" :wrapperCol="wideWrapperCol">
                <div class="global-search-wrapper" >
                  <a-auto-complete
                    :data-source="tagDataSource"
                    class="global-search"
                    @search="onSearch"
                    @select="onSelect"
                    @change="onTagChange"
                    size="large"
                    ref="tagSearch"
                    v-decorator="['tag']"
                    style="width: 100%"
                    :defaultActiveFirstOption="false"

                  >

                    <a-input


                      autocomplete="off"
                      v-model="tagInput"
                      v-decorator="['tagInput']"
                      @keydown="checkTag"
                    >
                      <a-button
                        slot="suffix"
                        style="margin-right: -12px"
                        class="search-btn"
                        size="large"
                        type="primary"


                        @click="tagAddFunction"
                      >
                        <a-icon type="search" />
                      </a-button>
                    </a-input>
                  </a-auto-complete>
                </div>

              </a-form-item>
            </a-col>
          </a-row>

          <a-row :span="24" v-show="selectedTagList && selectedTagList.length>0">
            <a-col span="3" align="right">
              <div class="ant-form-item-label">
                <label>已选标签</label>
              </div>
              </a-col>
            <a-col>
            <a-tag closable @close="closedTag(index)"  v-for="(tag,index) in selectedTagList" :key="tag">
              {{tag}}
            </a-tag>
            </a-col>
          </a-row>
          <a-row :span="24">
            <a-col span="24">
                  <j-select-plan @change="onPlanChange" v-decorator="['planList']"    ref="planComponent" />
            </a-col>

          </a-row>


          <a-row :span="24">
            <a-col :span="12" >
              <a-form-item label="测试成绩" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['testResult']" placeholder="请输入测试成绩"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" >
              <a-form-item label="测试项目" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                <j-dict-select-tag type="list" v-decorator="['testProject']" :trigger-change="true" dictCode="test_project" placeholder="请选择测试项目"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
          <a-col :span="12" v-show="!isAdd" >
            <a-form-item label="效果描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['effectiveDescription']" placeholder="请输入效果描述"></a-input>
            </a-form-item>
          </a-col>
          </a-row>
          <a-row>
          <a-col :span="24" v-show="!isAdd">
            <a-form-item label="效果视频" :labelCol="{span:3}" :wrapperCol="{span:18}">
              <j-video-upload isMultiple v-decorator="['effectiveVedio']"></j-video-upload>
            </a-form-item>
          </a-col>
          </a-row>
          <a-row>
          <a-col :span="12" v-show="!isAdd">
            <a-form-item label="训练时长" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['trainPeriod']" placeholder="请输入训练时长"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-show="!isAdd">
            <a-form-item label="训练频率" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['trainFrequency']" placeholder="请输入训练时长"></a-input>
            </a-form-item>
          </a-col>
          </a-row>
       </a-layout-content>
      <a-layout-sider  style="background: #fff; " width="32%">

        <a-form-item  :labelCol="labelCol2" :wrapperCol="wrapperCol2" >
          <j-video-upload isMultiple v-decorator="['vedioUrl']"></j-video-upload>
        </a-form-item>
      </a-layout-sider>
    </a-layout>
      </a-form>
    </j-form-container>



  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { httpAction, getAction } from '@/api/manage'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JVideoUpload from '@/components/jeecg/JVideoUpload'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JMultiSelectTag from "@/components/dict/JMultiSelectTag"
  import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
  import { validateDuplicateValue } from '@/utils/util'
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import JSelectPlan from './JSelectPlan';
  import { questionPlanQuery, questionTagQuery, questionTypeQuery} from '@/api/api'

  export default {
    name: 'QuestionForm',
    components: {
      JTreeSelect,
      JFormContainer,
      JVideoUpload,
      JDictSelectTag,
      JMultiSelectTag,
      JSearchSelectTag,
      JSelectPlan
    },
    data() {
      return {
        form: this.$form.createForm(this),
        model: {},
        confirmLoading: false,
        validatorRules: {
          age: {
            rules: [
              { required: true, message: '请输入年龄!'}
            ]
          },
          realname: {
            rules: [
              { required: true, message: '请输入姓名 !'}
            ]
          },
          avatar: {
            rules: [
              { required: true, message: '请输入头像!'}
            ]
          },
          phone: {
            rules: [
              { required: true, message: '请输入手机号码!'}
            ]
          },
        },

        tagDataSource:[],
        selectedTagList:[],
        planList:[],
        tagInput:'',
        demoLabelCol:{
          span:3
        },
        wideWrapperCol:{
          span:20
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        isAdd: true,
        validatorRules: {
        },


        url: {
          add: "/question/add",
          edit: "/question/edit",
          queryById: "/question/queryById"

        }
      }
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：false流程表单 true普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    mounted() {
    },

    methods: {
      add () {
        this.addBefore();
        this.edit({});
      },
      edit(record){
        this.visible = true;
        this.form.resetFields();
        this.planList = [];
        this.selectedTagList =[];
        this.model = Object.assign({}, record);
        this.visible = true;

        if(record.id == undefined) {
          this.isAdd = true
        }else {
          this.isAdd = false;
          this.questionPlanLoad();
          this.questionTagLoad();
          this.questionTypeLoad();
          //this.model.questionTypeId = '1';
          let fieldval = pick(this.model,'createTime','title','trainee','questionStatus','chadian','effectiveDescription','planList','questionTypeId',
            'description','testResult','testProject','vedioUrl','description','effectiveVedio','trainPeriod','trainFrequency')
          this.$nextTick(() => {
            this.form.setFieldsValue(fieldval)
          })


        }
      },
      checkTag(e){
          if(e.keyCode ==13){
            this.tagAddFunction(e);
          }
      },
      loadTagData(){
        let that = this;
        getAction(`/tag/list`,{pageSize:10000}).then(res=>{
          if(res.success){
            for(const item in res.result.records){
              that.tagDataSource.push( res.result.records[item].name);

            }
          }
        })
      },
      tagAddFunction(e){
        e.stopPropagation();
        this.pushTag(this.tagInput)
       this.tagInput = ''
      },
      onTagChange(s){

      },
      onSearch(){
        if(!this.tagDataSource.length){
          this.loadTagData();
        }
      },
      pushTag(tagName){
        if(tagName !=''){
          if(this.selectedTagList.length>0){
            for(let i in this.selectedTagList){
              if(tagName == this.selectedTagList[i]){
                return ;
              }
            }
          }

          this.selectedTagList.push(tagName);
        }
      },
      onSelect(s){
        this.tagInput =s;


      },
      //键盘事件
      keyPress(ev) {

      },
      closedTag(v){
        this.selectedTagList.splice(v,1);
      },
      onPlanChange(v){
         this.planList = v;
      },
      addBefore(){
        this.form.resetFields();
        this.$refs.planComponent.handleEmpty();
      },
      questionTagLoad() {
        var paramter = {
          id: this.model.id
        }
        questionTagQuery(paramter).then(res=>{
          if(res.code == 200) {
            for(var i = 0; i < res.result.length; i++) {
              var item = res.result[i]
              this.selectedTagList.push(item.tagName)
            }
          }
        })
      },
      questionPlanLoad() {
        var paramter = {
          id: this.model.id
        }
        const that = this;
        questionPlanQuery(paramter).then(res=>{
          if(res.code == 200) {

            for(var i = 0; i < res.result.length; i++) {
              var item = res.result[i]
              var paramter = {
                id: item.planId,
                title: item.questionPlanName
              }
              this.planList.push(paramter)
            }

          }
        })
      },
      questionTypeLoad() {
        var paramter = {
          id: this.model.id
        }
        const that = this;
        const questionTypeId = [];
        questionTypeQuery(paramter).then(res=>{
          if(res.code == 200) {
            for(let i = 0; i < res.result.length; i++) {
              let item = res.result[i]
              questionTypeId.push(item.questionTypeId);
            }
            that.questionTypeId =questionTypeId.join(",");
            let fieldval = pick({"questionTypeId":that.questionTypeId},"questionTypeId")
            that.$nextTick(() => {
              that.form.setFieldsValue(fieldval)

            })

          }
        })
      },
      handleSave(){
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
               console.log(values)
            const myQuestionPlanList = [];
            for(let index in that.planList){
              myQuestionPlanList.push({planId:that.planList[index].id});
            }
            values.myQuestionPlanList = myQuestionPlanList;
            const tagMappingList =  [];
            for(const index in that.selectedTagList){
              tagMappingList.push({tagName:that.selectedTagList[index]});
            }
             values.tagMappingList = tagMappingList;
             const questionTypeList =  values.questionTypeId.split(",");
             const questionTypeMappingList = []
             for(const index in questionTypeList){
               questionTypeMappingList.push({questionTypeId:questionTypeList[index],mappingType:1});
             }
             values.questionTypeMappingList = questionTypeMappingList;

            let url = this.url.add, method = 'post'
            if (this.model.id) {
              url = this.url.edit
            }
            this.confirmLoading = true
            let formData = Object.assign(this.model, values);
            httpAction(url, formData, method).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.$emit('ok')
                this.close()
              } else {
                this.$message.warning(res.message)
              }
            }).finally(() => {
              this.confirmLoading = false
            })

          }
        })
      },


      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        main.tag = this.selectedTagList;
        main.planList = this.planList;
        return {
          ...main // 展开

        }
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          })
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'createTime','title','effectiveDescription','trainee','questionStatus','chadian','description','testResult','testProject','vedioUrl','questionTypeId'))
      },

    }
  }
</script>

<style scoped>
  .global-search-wrapper {
    padding-right: 50px;
  }

  .global-search {
    width: 100%;
  }

  .global-search.ant-select-auto-complete .ant-select-selection--single {
    margin-right: -46px;
  }

  .global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input:not(:last-child) {
    padding-right: 62px;
  }

  .global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input-suffix button {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }

  .global-search-item {
    display: flex;
  }

  .global-search-item-desc {
    flex: auto;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .global-search-item-count {
    flex: none;
  }
</style>
